import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import { adminAPI } from '../api/api'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { title: '登录', requiresAuth: false }
    },
    {
      path: '/',
      name: 'dashboard',
      component: HomeView,
      meta: { title: '控制台', requiresAuth: true }
    },
    {
      path: '/store/index',
      name: 'store',
      component: () => import('../views/store/StoreIndex.vue'),
      meta: { title: '商品管理', requiresAuth: true }
    },
    {
      path: '/order/index',
      name: 'order',
      component: () => import('../views/order/OrderIndex.vue'),
      meta: { title: '订单管理', requiresAuth: true }
    },
    {
      path: '/user/index',
      name: 'user',
      component: () => import('../views/user/UserIndex.vue'),
      meta: { title: '用户管理', requiresAuth: true }
    },
    {
      path: '/sys/menu',
      name: 'user',
      component: () => import('../views/sys/MenuView.vue'),
      meta: { title: '菜单管理', requiresAuth: true }
    },
    {
      path: '/admin/list',
      name: 'adminlist',
      component: () => import('../views/admin/AdminList.vue'),
      meta: { title: '管理员列表', requiresAuth: true }
    },
    {
      path: '/admin/role',
      name: 'adminrole',
      component: () => import('../views/admin/AdminRole.vue'),
      meta: { title: '角色管理', requiresAuth: true }
    },
    {
      path: '/ad',
      name: 'ad',
      component: () => import('../views/ad/AdIndex.vue'),
      meta: { title: '广告配置', requiresAuth: true }
    }
  ]
})

// 记录最后一次验证登录状态的时间和锁
let lastAuthCheck = 0;
let isChecking = false;
// 全局加载计数器
let loadingCounter = 0;
let globalLoading = null;

// 显示全局加载状态
const showGlobalLoading = () => {
  if (loadingCounter === 0 && !globalLoading) {
    // 使用Element Plus的全局加载
    import('element-plus').then(({ ElLoading }) => {
      globalLoading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(255, 255, 255, 0.7)',
      });
    });
  }
  loadingCounter++;
};

// 隐藏全局加载状态
const hideGlobalLoading = () => {
  loadingCounter = Math.max(0, loadingCounter - 1);
  if (loadingCounter === 0 && globalLoading) {
    globalLoading.close();
    globalLoading = null;
  }
};

// 设置页面标题和路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - CRMEB_JAVA21` : 'CRMEB_JAVA21'

  // 如果不需要鉴权或者是登录页面，直接放行
  if (to.meta.requiresAuth === false) {
    next();
    return;
  }

  // 快速检查：如果本地存储有登录状态且目标不是登录页，直接允许访问
  const hasLocalLoginStatus = localStorage.getItem('isLoggedIn') === 'true';
  if (hasLocalLoginStatus && to.path !== '/login') {
    next();

    // 后台预加载菜单，不阻塞导航
    if (!to.path.includes('/login')) {
      setTimeout(() => {
        adminAPI.getMenus().catch(err => {
          console.warn('路由守卫预加载菜单失败:', err);
          // 错误不阻塞导航
        });
      }, 100);
    }
    return;
  }

  // 防止频繁请求和循环跳转
  const now = Date.now();
  if (isChecking || (now - lastAuthCheck < 3000)) {
    // 如果已经在检查中或者距离上次检查小于3秒，直接放行
    next();
    return;
  }

  // 主要验证登录状态
  try {
    isChecking = true;
    lastAuthCheck = now;

    // 非登录页跳转时显示加载状态
    if (to.path !== '/login') {
      showGlobalLoading();
    }

    // 使用封装好的API检查登录状态
    const result = await adminAPI.getStatus();
    const isLoggedIn = result.code === 200;

    // 保存登录状态到本地存储
    if (isLoggedIn) {
      localStorage.setItem('isLoggedIn', 'true');
    } else {
      localStorage.removeItem('isLoggedIn');
    }

    if (isLoggedIn) {
      // 已登录，允许访问
      // 预加载菜单，但不等待结果，保持导航流畅性
      if (to.path !== '/login') {
        adminAPI.getMenus().catch(err => {
          console.warn('预加载菜单失败:', err);
          // 错误不阻塞导航
        });
      }
      next();
    } else {
      // 未登录，重定向到登录页
      // 防止循环重定向
      if (to.path === '/login') {
        next();
      } else {
        next('/login');
      }
    }
  } catch (error) {
    console.error('检查登录状态失败', error);
    // 清除本地登录状态
    localStorage.removeItem('isLoggedIn');

    // 发生错误时，避免循环重定向
    if (to.path === '/login') {
      next();
    } else {
      next('/login');
    }
  } finally {
    // 释放锁
    isChecking = false;

    // 在afterEach中执行会更好，但这里需要确保无论流程如何都隐藏loading
    setTimeout(() => {
      hideGlobalLoading();
    }, 500); // 延迟500ms确保页面有时间渲染
  }
});

// 路由加载完成后
router.afterEach(() => {
  // 确保加载状态消失
  setTimeout(() => {
    hideGlobalLoading();
  }, 500);
});

export default router
